package 简单.双指针;

/**
 * 编写一个函数，以字符串作为输入，反转该字符串中的元音字母。
 * a o e i u
 * <p>
 * 来源：https://leetcode-cn.com/problems/reverse-vowels-of-a-string/
 */
public class 反转字符串中的元音字母_345 {

    public static void main(String[] args) {

        System.out.println(efficientReverseVowels("leetcode"));

    }

    //双指针+stringbuilder
    public static String reverseVowels(String s) {
        //使用stringbuilder节省空间
        StringBuilder stringBuilder = new StringBuilder(s);
        int right = stringBuilder.length() - 1, left = 0;
        char temp = '2';
        while (right > left) {
            if (!isYuanYin(stringBuilder.charAt(right))) {
                right--;
            }
            if (!isYuanYin(stringBuilder.charAt(left))) {
                left++;
            }
            if (isYuanYin(stringBuilder.charAt(right)) && isYuanYin(stringBuilder.charAt(left))) {
                temp = stringBuilder.charAt(right);
                stringBuilder.setCharAt(right, stringBuilder.charAt(left));
                stringBuilder.setCharAt(left, temp);
                right--;
                left++;
            }
        }
        return stringBuilder.toString();
    }

    //双指针+数组
    public static String efficientReverseVowels(String s) {
        char[] chars = s.toCharArray();
        int right = chars.length - 1, left = 0;
        char temp;
        while (right > left) {
            if (!isYuanYin(chars[right])) {
                right--;
            }
            if (!isYuanYin(chars[left])) {
                left++;
            }
            if (isYuanYin(chars[left]) && isYuanYin(chars[right])) {
                temp = chars[right];
                chars[right] = chars[left];
                chars[left] = temp;
                right--;
                left++;
            }
        }
        return String.valueOf(chars);
    }

    public static boolean isYuanYin(char c) {
        if (c == 'a' || c == 'o' || c == 'e' || c == 'i' || c == 'u' || c == 'A' || c == 'O' || c == 'E' || c == 'I' || c == 'U') {
            return true;
        }
        return false;
    }
}
